<?php

namespace frontend\models;

use common\models\User;
use yii\base\Model;
use Yii;
use frontend\models\WB_UserProfile;
use frontend\models\WB_UserAccount;
use frontend\models\WB_UserPayRecord;
use yii\helpers\ArrayHelper;

/**
 * Signup form
 */
class SignupForm extends Model {

    public $username;
    public $phone;
    public $password;
    public $repassword;
    public $invite_code;
    public $truename;
    public $alipay;
    public $qq;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required', "message" => "用户名不能为空"],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => '用户名已存在'],
            ['username', 'string', 'min' => 2, 'max' => 255],
//            ['phone', 'filter', 'filter' => 'trim'],
//            ['phone', 'required'],
//            ['phone', "match", "pattern" => "/^((0\\d{2,3}(-){0,1}\\d{7,8})|(1[3584]\\d{9}))$/", "message" => "联系方式格式不正确"],
//            ['phone', 'string', 'max' => 255],
            ['password', 'required', "message" => "密码不能为空"],
            ['password', 'string', 'min' => 6],
//            [["alipay"], "required", "message" => "请输入支付宝账号"],
//            [["alipay"], "checkalipay"],
            //[["alipay"], "unique", 'targetClass' => '\common\models\UserProfile', "message" => "该支付宝账号已经被注册，请更换"],
            [["repassword"], "compare", "compareAttribute" => "password", "message" => "两次密码不一致"],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup() {
        if (!$this->validate()) {
            return null;
        }
        $trans = Yii::$app->db->beginTransaction();
        try {
            $user = new User();
            $user->username = $this->username;
            $user->role = 1;
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->generatePasswordResetToken();
            if ($user->save()) {
                //保存基本信息
                $res = WB_UserProfile::find()->where("userid=" . $user->id)->one();
                $userprofile = $res instanceof WB_UserProfile ? $res : new WB_UserProfile();
                $userprofile->userid = $user->id;
                $userprofile->username = $this->username;
                $userprofile->invite_code = $this->invite_code;
                $userprofile->truename = $this->truename;
                $userprofile->alipay = $this->alipay;
                $userprofile->qq = $this->qq;
                $userprofile->gradeid = 1;
                $userprofile->phone = $this->phone;
                if($userprofile->save())
                
                //充值代理级别
                WB_UserPayRecord::createRecord($user->id, 0, 1, 1);
                //邀请人，获得返利
            }
            $trans->commit();
            return $user;
        } catch (Exception $ex) {
            $trans->rollBack();
            throw $ex;
        }
    }

    public function checkalipay($attribute, $params) {
        if (!$this->hasErrors()) {
            $emailpattern = '/^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$/';
            $phonepattern = '/^((0\\d{2,3}(-){0,1}\\d{7,8})|(1[3584]\\d{9}))$/';
            if (!(preg_match($emailpattern, $this->alipay) || preg_match($phonepattern, $this->alipay))) {
                $this->addError($attribute, '支付宝账号只能输入邮箱和手机号码！');
            }
        }
    }

}
